package StudyCode.summary.BufferAndChannel;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class DecodeDisplayContentByteBuffer {
	static Thread current;
	static final Path path = Paths.get("E:\\Copy", "1.txt");

	public static void main(String[] args) {
		CompletionHandler<Integer, ByteBuffer> handler = new CompletionHandler<Integer, ByteBuffer>() {
			String encoding = System.getProperty("file.encoding");

			@Override
			public void completed(Integer result, ByteBuffer attachment) {
				System.out.println("读取 bytes: " + result);
				attachment.flip();
				System.out.print(Charset.forName(encoding).decode(attachment));
				attachment.clear();
				current.interrupt();
			}

			@Override
			public void failed(Throwable exc, ByteBuffer attachment) {
				System.out.println(attachment);
				System.out.println("错误:" + exc);
				current.interrupt();
			}
		};
		try (AsynchronousFileChannel asynchronousFileChannel = AsynchronousFileChannel
				.open(path, StandardOpenOption.READ)) {
			current = Thread.currentThread();
			ByteBuffer buffer = ByteBuffer.allocate(100);
			asynchronousFileChannel.read(buffer, 0, buffer, handler);
			System.out.println("等待 ...\n");
			try {
				current.join();
			} catch (InterruptedException e) {
			}
			System.out.println("结束");
		} catch (Exception ex) {
			System.err.println(ex);
		}
	}
}
